import { defineStore } from 'pinia'
import type { IHandleApi } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IProduct } from '@/types/product'
import {
  addProductApi,
  deleteProductApi,
  queryProductCategoryApi,
  queryProductListApi,
  updateProductApi
} from '@/apis/product.ts'
import { ImagePathEnum } from '@/types'

export const useProductStore = defineStore('product', {
  state: () => ({
    productList: [] as IProduct[],
    queryInfo: {
      category: '',
      order: 'date'
    },
    productApiType: 'ADD' as IHandleApi,
    categoryList: [] as string[],
    currentProduct: {
      category: '',
      channel: '',
      expiryDate: '',
      price: 0,
      purchaseDate: '',
      purchaser: '',
      name: '',
      imageUrl: ''
    } as IProduct,
    productImagePath: ImagePathEnum.PRODUCT,
    pageInfo: {
      currentPage: 1,
      pageSize: 3,
      totalSize: 1
    },
    isScrollEnd: false,
    isRefresh: false
  }),
  actions: {
    async queryProductList() {
      this.productList = await queryProductListApi(this.queryInfo)
    },
    async queryProductCategory() {
      this.categoryList = await queryProductCategoryApi()
    },
    async handleProductApi(product: IProduct) {
      switch (this.productApiType) {
        case 'ADD':
          await addProductApi(product)
          ElMessage.success('新增物品成功')
          break
        case 'UPDATE':
          await updateProductApi(product.id as number, product)
          ElMessage.success('更新物品成功')
          break
        case 'DELETE':
          await deleteProductApi(product.id as number)
          ElMessage.success('删除物品成功')
          break
        default:
          break
      }
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryProductList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyProduct(): IProduct {
      return {
        category: '',
        channel: '',
        expiryDate: '',
        price: 0,
        purchaseDate: '',
        purchaser: '',
        name: '',
        imageUrl: ''
      }
    }
  }
})
